<template>
  <CommonPage show-footer title="医生">
    <template #action>
      <div>
        <n-button type="primary" secondary @click="$table?.handleExport()">
          <TheIcon icon="mdi:download" :size="18" class="mr-5" />
          导出
        </n-button>
        <n-button type="primary" class="ml-16" @click="handleAdd">
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />
          新建医生
        </n-button>
      </div>
    </template>

    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :extra-params="extraParams"
      :scroll-x="1200"
      :columns="columns"
      :get-data="api.getDoctors"
      @on-checked="onChecked"
      @on-data-change="(data) => (tableData = data)"
    >
      <template #queryBar>
        <QueryBarItem label="医生姓名" :label-width="65">
          <n-input
            v-model:value="queryItems.query"
            type="text"
            placeholder="请输入医生姓名"
            @keypress.enter="$table?.handleSearch"
          />
        </QueryBarItem>
        <QueryBarItem label="所属科室" :label-width="65">
          <n-tree-select
            v-model:value="queryItems.dept"
            :options="departments"
            label-field="dept_name"
            key-field="id"
            children-field="children"
          />
        </QueryBarItem>
      </template>
    </CrudTable>
    <!-- 新增/编辑/查看 -->
    <CrudModal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :loading="modalLoading"
      :show-footer="modalAction !== 'view'"
      @on-save="handleSave"
    >
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
        :disabled="modalAction === 'view'"
      >
      <n-form-item
          label="姓名"
          path="nickname"
          :rule="{
            required: true,
            message: '请输入医生姓名',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.nickname" placeholder="请输入医生姓名" />
      </n-form-item> 
      
        <n-form-item label="头像" path="icon">
          <n-upload
            ref="uploadRef"
            list-type="image-card"
            action=""
            :custom-request="Upload"
            :max="1"
          >
          <img :src="modalForm.avatar_url" style="width: 100%">
          </n-upload>
        </n-form-item>
        <n-form-item
          label="所属部门"
          path="dept_name"
          :rule="{
            required: true,
            message: '请选择所属部门',
            trigger: ['input', 'blur'],
          }"
        >
          <n-select
            v-model:value="modalForm.dept_name"
            :options="options"
            @update:value="handleUpdateValue"
          ></n-select>
        </n-form-item>

        <n-form-item
          label="职务"
          path="duties"
          :rule="{
            required: true,
            message: '请输入医生职务',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.duties" placeholder="请输入医生职务" />
      </n-form-item> 

        <n-form-item
          label="特长"
          path="speciality"
          :rule="{
            required: true,
            message: '请输入医生特长',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input
            v-model:value="modalForm.speciality"
            placeholder="请输入医生特长"
            type="textarea"
            :autosize="{
              minRows: 3,
              maxRows: 5,
            }"
          />
        </n-form-item>
        <n-form-item
          label="教育背景"
          path="educational_background"
          :rule="{
            required: true,
            message: '请输入医生教育背景',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input
            v-model:value="modalForm.educational_background"
            placeholder="请输入医生教育背景"
            type="textarea"
            :autosize="{
              minRows: 3,
              maxRows: 5,
            }"
          />
        </n-form-item>
        <n-form-item
          label="工作经验"
          path="work_experience"
          :rule="{
            required: true,
            message: '请输入医生工作经验',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input
            v-model:value="modalForm.work_experience"
            placeholder="请输入医生工作经验"
            type="textarea"
            :autosize="{
              minRows: 3,
              maxRows: 5,
            }"
          />
        </n-form-item>
        <n-form-item
          label="研究方向"
          path="research_direction"
          :rule="{
            required: true,
            message: '请输入医生研究方向',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input
            v-model:value="modalForm.research_direction"
            placeholder="请输入医生研究方向"
            type="textarea"
            :autosize="{
              minRows: 3,
              maxRows: 5,
            }"
          />
        </n-form-item>
        <n-form-item
          label="学术职位"
          path="academic_positions"
          :rule="{
            required: true,
            message: '请输入医生学术职位',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input
            v-model:value="modalForm.academic_positions"
            placeholder="请输入医生学术职位"
            type="textarea"
            :autosize="{
              minRows: 3,
              maxRows: 5,
            }"
          />
        </n-form-item>
      </n-form>
    </CrudModal>
  </CommonPage>
</template>

<script setup>
import { NButton, NSwitch } from 'naive-ui'
import { formatDateTime, renderIcon, isNullOrUndef } from '@/utils'
import { useCRUD } from '@/composables'
import api from './api'
import baseApi from '@/api'

defineOptions({ name: 'Doctor' })

const $table = ref(null)
/** 表格数据，触发搜索的时候会更新这个值 */
const tableData = ref([])
const options = ref([])
const departments = ref([])
/** QueryBar筛选参数（可选） */
const queryItems = ref({
  dept: 0
})
/** 补充参数（可选） */
const extraParams = ref({})

onActivated(async () => {
  $table.value?.handleSearch()
  const dep = await (await api.getDepartments()) 
  departments.value = dep.data
  const res = await api.getParentDepartments({ pageNo: 1, pageSize: 100 })
  for (let i = 0; i < res.data.pageData.length; i++) {
    options.value.push({
      label: res.data.pageData[i].dept_name,
      value: res.data.pageData[i].id,
    })
  }
})

const columns = [
  { title: '序号', key: 'id', width: 50, ellipsis: { tooltip: true } },
  { title: '姓名', key: 'nickname', width: 60, ellipsis: { tooltip: true } },
  { title: '职务', key: 'duties', width: 80, ellipsis: { tooltip: true } },
  { title: '所属科室', key: 'dept_name', width: 100, ellipsis: { tooltip: true } },
  { title: '特长', key: 'speciality', width: 180 },
  { title: '教育背景', key: 'educational_background', width: 60, ellipsis: { tooltip: true }},
  { title: '工作经历', key: 'work_experience', width: 60, ellipsis: { tooltip: true } },
  { title: '研究方向', key: 'research_direction', width: 60, ellipsis: { tooltip: true } },
  { title: '学术职务', key: 'academic_positions', width: 60 , ellipsis: { tooltip: true }},
  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => handleView(row),
          },
          { default: () => '查看', icon: renderIcon('majesticons:eye-line', { size: 14 }) }
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            onClick: () => handleEdit(row),
          },
          { default: () => '编辑', icon: renderIcon('material-symbols:edit-outline', { size: 14 }) }
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: renderIcon('material-symbols:delete-outline', { size: 14 }),
          }
        ),
      ]
    },
  },
]

// 选中事件
function onChecked(rowKeys) {
  if (rowKeys.length) $message.info(`选中${rowKeys.join(' ')}`)
}
function handleUpdateValue(string, SelectOption) {
  modalForm.value.parent_name = SelectOption.label
  modalForm.value.parent_id = SelectOption.value
}
const Upload = ({ file,data,headers,withCredentials,action,onFinish}) => {
  let formdata = new FormData()    //formdata格式
  formdata.append('image', file.file)
  formdata.append('business', 'image')
  // 接口请求
  baseApi.uploadImage(formdata).then((res) => {
      console.log(res)
      modalForm.value.avatar_url=res.data.url
      // 注意清空，要不接口会重复调用
      onFinish()
    })
    .catch((err) => {
      console.log(err)
    })

  
}
const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleView,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '医生',
  initForm: { author: '大脸怪' },
  doCreate: api.addPost,
  doDelete: api.deleteUser,
  doUpdate: api.updateDoctor,
  refresh: () => $table.value?.handleSearch(),
})
</script>
